package com.qiyun.erp.util.interceptor;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.qiyun.erp.auth.emp.vo.EmpModel;
import com.qiyun.erp.auth.res.business.ebi.ResEbi;
import com.qiyun.erp.auth.res.vo.ResModel;
import com.qiyun.erp.util.exception.AppException;
import org.apache.struts2.ServletActionContext;

import java.util.List;

public class AuthInterceptor extends AbstractInterceptor {
    private ResEbi resEbi;

    public void setResEbi(ResEbi resEbi) {
        this.resEbi = resEbi;
    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        String actionName = invocation.getProxy().getAction().getClass().getName();
        String methodName = invocation.getProxy().getMethod();
        String allName = actionName + "." + methodName;
        String resAll = ServletActionContext.getServletContext().getAttribute("allRes").toString();

        if (!resAll.contains(allName)) {
            return invocation.invoke();
        }

        if ("cn.itcast.erp.auth.emp.web.EmpAction.login".equals(allName)) {
            return invocation.invoke();
        }

        EmpModel loginEm = (EmpModel) ActionContext.getContext().getSession().get(EmpModel.EMP_LOGIN_USER_OBJECT_NAME);
        if (loginEm == null) {
            return "noLogin";
        }

        List<ResModel> resLists = resEbi.getAllBuEmp(loginEm.getUuid());

        for (ResModel rm : resLists) {
            if (rm.getUrl().equals(allName)) {
                return invocation.invoke();
            }
        }

        throw new AppException("权限不足 无法操作！！");
    }
}
